<template>
  <view class="head_comp" :style="transparent ? boxBg : 'background: #ffffff;'">
    <view class="left_back">
      <text v-if="showBack" class="iconfont icon-xiangzuo" @click="goBack" :style="transparent ? backBtn : ''"></text>
    </view>
    <view class="title_box" :style="transparent ? 'opacity:' + scrollTop / maxHeight : ''">
      <text class="title">{{title}}</text>
    </view>
    <view class="right_action" :style="transparent ? 'opacity:' + scrollTop / maxHeight : ''">
      <slot name="action"></slot>
    </view>
  </view>
</template>

<script>
  export default {
    components: {},
    props: {
      title: {
        type: String
      },
      scrollTop: {
        // 屏幕滚动高度，计算透明度用
        type: Number,
        default: 0,
      },
      transparent: {
        // 控制是否根据页面滚动自动修改透明度
        type: Boolean,
        default: true,
      },
      showBack: {
        // 控制是否展示返回按钮
        type: Boolean,
        default: true,
      }
    },
    computed: {
      boxBg() {
        // head最外层盒子背景色
        let color = `background: rgba(255, 255, 255, ${this.scrollTop / this.maxHeight})`
        return color
      },
      backBtn() {
        // 返回按钮字体色+背景色
        let color = ''
        if (this.scrollTop === 0) {
          color = 'color: rgba(255, 255, 255, 1); background: rgba(0, 0, 0, 1)'
        } else if (this.scrollTop <= this.maxHeight) {
          color =
            `color: rgba(${Math.abs(1 - this.scrollTop / this.maxHeight) * 255}, ${Math.abs(1 - this.scrollTop / this.maxHeight) * 255}, ${Math.abs(1 - this.scrollTop / this.maxHeight) * 255}, 1); background: rgba(0, 0, 0, ${Math.abs(1 - this.scrollTop / this.maxHeight)})`
        } else {
          color = 'rgba(0, 0, 0, 1); background: rgba(255, 255, 255, 1)'
        }
        return color
      }
    },
    data() {
      return {
        maxHeight: 175, // 透明度阈值滚动高度
      }
    },
    created() {},
    methods: {
      goBack() {
        var pages = getCurrentPages();
        if (pages.length > 1) {
          // 返回上一页
          uni.navigateBack({
            delta: 1
          });
        } else {
          uni.redirectTo({
            url: '/pages/home/index'
          });
        }
      },
    }
  }
</script>

<style scoped lang="scss">
  .head_comp {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 2000;
    padding-top: var(--status-bar-height);
    min-height: 50px;
    .left_back {
      display: inline-block;
      text-align: center;
      width: 120upx;
      line-height: 50px;
      .iconfont {
        border-radius: 50%;
        padding: 10upx;
        font-size: 40upx;
      }
    }
    .title_box {
      display: inline-block;
      text-align: center;
      width: calc(100% - 240upx);
      line-height: 50px;
      font-size: 35upx;
    }
    .right_action {
      display: inline-block;
      text-align: center;
      width: 120upx;
      line-height: 50px;
      font-size: 35upx;
    }
  }
</style>
